package com.guofeng.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

//synchronized 单应用加锁
@RestController
@RequestMapping("index")
public class IndexController2 {

    @Autowired
    StringRedisTemplate template;

    @RequestMapping("/buy2")
    public synchronized String index() {
        String result = template.opsForValue().get("goods");
        int total = result == null ? 0 : Integer.parseInt(result);
        if (total > 0) {
            int realTotal = total - 1;
            template.opsForValue().set("goods", String.valueOf(realTotal));
            System.out.println("购买商品成功，库存还剩：" + realTotal + "件， 服务端口为8001");
            return "购买商品成功，库存还剩：" + realTotal + "件， 服务端口为8001";
        } else {
            System.out.println("购买商品失败，服务端口为8001");
        }
        return "购买商品失败，服务端口为8001";
    }
}
